package Demo41;

/**
 * N 字形变换
 * https://leetcode.cn/problems/zigzag-conversion/
 * 1. 先处理边界问题
 * 2. 先计算第一行
 * 3. 计算第2行到 len - 2行
 * 4. 计算len - 1行
 */

class Solution {
    public String convert(String ss, int numRows) {
        if(numRows == 1) return ss;
        int len = ss.length(),d = numRows * 2 - 2;
        StringBuilder ret = new StringBuilder();

        for(int i = 0;  i < len;i+=d) ret.append(ss.charAt(i));

        for(int i = 1; i < numRows - 1;i++) {
            for(int k = d - i,j = i; j < len; j += d, k += d) {
                ret.append(ss.charAt(j));
                if(k < len)
                    ret.append(ss.charAt(k));
            }
        }

        for(int i = numRows - 1;  i < len;i+=d) ret.append(ss.charAt(i));
        return ret.toString();
    }

    public String convert1(String ss, int numRows) {
        if(numRows == 1) {
            // 公差为0 ,n 为1 , 不需要变形
            return ss;
        }
        int d = (2 * numRows) - 2; // 公差
        char[] s = ss.toCharArray();
        int len = s.length;
        char[] ret = new char[len];
        int index = 0;
        // 处理第一行
        for(int i = 0; i < len;i += d) {
            ret[index] = s[i];
            index++;
        }
        for(int i = 1; i <= numRows - 2;i++) {
            int j = d - i;
            for(int k = i; k < len; k += d) {
                ret[index++] = s[k];
                if(j < len) ret[index++] =  s[j];
                j += d;
            }
        }
        // 处理最后一行
        for(int i = numRows - 1; i < len;i += d) {
            ret[index++] = s[i];
        }
        return String.valueOf(ret);
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String ret = solution.convert("PAYPALISHIRING",3);
        System.out.println(ret);
    }
}